package logic

import (
	"context"
	"eight-dimensional-mall/goods_srv/model/mysql"
	"eight-dimensional-mall/goods_srv/model/redis"
	"errors"

	"eight-dimensional-mall/goods_srv/goods"
	"eight-dimensional-mall/goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCartLogic {
	return &CreateCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateCartLogic) CreateCart(in *goods.CreateCartReq) (*goods.CreateCartResp, error) {
	g := mysql.Goods{}
	err := g.GetGoodsInfo(int(in.GoodsId))
	if err != nil {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}
	if g.GoodsStock < in.Num {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}
	err = redis.AddCart(int(in.UserId), int(in.Num), int(in.GoodsId), g)
	if err != nil {
		logx.Error("购物车添加失败")
		return nil, errors.New("购物车添加失败")
	}
	return &goods.CreateCartResp{}, nil
}
